//
//  HLEViewController.m
//  RPCFCADemo
//
//  Created by john on 10/18/2022.
//  Copyright (c) 2022 john. All rights reserved.
//

#import "HLEViewController.h"
#import "RPNetworkUitls.h"
#import "RPGloabManage.h"
#import "RPDBManage.h"



//#define RPCompany @"CYFX"
//#define RPOrgan @"SZHQ"
//#define URL @"http://43jy135477.oicp.vip:17406"
//#define URL @"https://121.4.208.208:843"


 
@interface HLEViewController () <UITextFieldDelegate>
@property(nonatomic, strong) UILabel *loginLabel;
@property(nonatomic, strong) RPAccountView *accountView;
@property(nonatomic, strong) RPPasswordView *passwordView;
@property(nonatomic, strong) UIButton *loginBtn;
@property (nonatomic,strong)UIButton *btnSelect;
@property(nonatomic, strong) UILabel *permitLabel;

@property (nonatomic,strong)UIButton *securePrivacybtn;
@property (nonatomic,strong)UIButton *securePermitbtn;


@end

@implementation HLEViewController

- (void)addObserver
{
    for (NSString *name in @[ UIApplicationUserDidTakeScreenshotNotification]) {
      [[NSNotificationCenter defaultCenter] addObserver:self
                                               selector:@selector(appDidMoveToForeground)
                                                   name:name
                                                 object:nil];
    }
}

- (void)appDidMoveToForeground
{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    [QMUITips showError:@"禁止录屏截屏，谢谢配合" inView:window hideAfterDelay:2];
}


- (void)showNormalDialogViewController {
    QMUIDialogViewController *dialogViewController = [[QMUIDialogViewController alloc] init];
    dialogViewController.title = @"标题";
    UIView *contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 100)];
    contentView.backgroundColor = UIColorWhite;
    UILabel *label = [[UILabel alloc] qmui_initWithFont:UIFontMake(14) textColor:UIColorBlack];
    label.text = @"自定义contentView";
    [label sizeToFit];
    label.center = CGPointMake(CGRectGetWidth(contentView.bounds) / 2.0, CGRectGetHeight(contentView.bounds) / 2.0);
    [contentView addSubview:label];
    dialogViewController.contentView = contentView;
    [dialogViewController addCancelButtonWithText:@"取消" block:nil];
    weakify(self);
    [dialogViewController addSubmitButtonWithText:@"确定" block:^(QMUIDialogViewController *aDialogViewController) {
        strongify(self);
        [aDialogViewController hide];
        self.fd_prefersNavigationBarHidden = YES;
        self.view.backgroundColor = [UIColor colorWithHexString:@"#4BA8FF"];
        [self initUI];
    }];
    [dialogViewController show];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.fd_prefersNavigationBarHidden = YES;
    self.view.backgroundColor = [UIColor colorWithHexString:@"#4BA8FF"];
    [self initUI];
    
    [self addObserver];

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self clearPassword];
}

- (void)initUI
{
    [self.view addSubview:self.loginLabel];
    
    
    LLNavgationBarView *nav = [LLNavgationBarView addBarTo:self.view];
    nav.backgroundColor = [UIColor clearColor];
    
    LLBarButtonItem *item = [LLBarButtonItem barButtonItemWithTitle:@"设置" handler:^(LLBarButtonItem *barButtonItem) {
        NSLog(@"==== click");
        RPSettingViewController *settingVC = [[RPSettingViewController alloc] init];
        settingVC.popBlock = ^{
            self.accountView.accountField.text = RPAccount;
        };
        [self.navigationController pushViewController:settingVC animated:YES];
    }];
    item.titleLabel.textColor = UIColor.whiteColor;
    nav.rightBarButtonItem = item;
    

    MyRelativeLayout *layout2 = [self createLayout2];  //子视图整体垂直居中的布局
    layout2.centerXPos.equalTo(@0);
    layout2.centerYPos.equalTo(@0);
    layout2.heightSize.equalTo(@400);
    layout2.widthSize.equalTo(self.view.widthSize);    //宽度等于高度
    [self.view addSubview:layout2];
}


//子视图整体垂直居中的布局
-(MyRelativeLayout*)createLayout2
{
    MyRelativeLayout *layout = [MyRelativeLayout new];
    
    self.loginLabel.topPos.equalTo(@0);
    self.loginLabel.leftPos.equalTo(@24);
    [layout addSubview:self.loginLabel];
    
    
    RPAccountView *v1 = self.accountView;
    v1.widthSize.equalTo(self.view.widthSize);    //宽度等于高度
    v1.heightSize.equalTo(@50);
    v1.centerXPos.equalTo(@0);
    [layout addSubview:v1];
    
    
    UIView *v2 = self.passwordView;
    v2.widthSize.equalTo(self.view.widthSize);    //宽度等于高度
    v2.heightSize.equalTo(@50);
    v2.centerXPos.equalTo(@0);
    [layout addSubview:v2];
    
    
//    MyFlexLayout *permitLayout = [MyFlexLayout flowLayoutWithOrientation:MyOrientation_Horz arrangedCount:2];
//    permitLayout.myHeight = MyLayoutSize.wrap;
//    permitLayout.width = self.view.width;
//    [layout addSubview:permitLayout];
//    permitLayout.myFlex.align_items(MyFlexGravity_Space_Between);

    MyFlexLayout *permitLayout = [MyFlexLayout new].myFlex
    .flex_grow(1)
    .width(self.view.width)
    .height(MyLayoutSize.wrap)
    .align_self(MyFlexGravity_Space_Between)
    .addTo(layout);
    
    permitLayout.paddingLeft = 20;
    permitLayout.paddingRight = 20;

    
    [permitLayout addSubview:self.btnSelect];
    self.btnSelect.height = 22;
    self.btnSelect.width = 22;
    [permitLayout addSubview:self.permitLabel];
    permitLayout.myFlex.justify_content(MyFlexGravity_Flex_Start);
    
    
    
    MyFlexLayout *linkLayout = [MyFlexLayout new].myFlex
    .flex_grow(1)
    .width(self.view.width)
    .height(MyLayoutSize.wrap)
    .align_self(MyFlexGravity_Space_Between)
    .addTo(layout);
    
    linkLayout.paddingLeft = 40;
    linkLayout.paddingRight = 40;

    [linkLayout addSubview:self.securePrivacybtn];
    [linkLayout addSubview:self.securePermitbtn];
    linkLayout.myFlex.justify_content(MyFlexGravity_Space_Between);
    
    self.loginBtn.heightSize.equalTo(@40);
    self.loginBtn.leftPos.equalTo(@20);
    self.loginBtn.rightPos.equalTo(@20);
    self.loginBtn.centerXPos.equalTo(@0);
    [layout addSubview:self.loginBtn];

    //通过为centerYPos等于一个数组值，表示v1和v2在父布局视图之内整体垂直居中,这里的20表示v1和v2之间还有20的间隔。
//    v1.centerYPos.equalTo(@[v2.centerYPos.offset(10),titleLabel.centerYPos.offset(10)]);
    self.loginLabel.centerYPos.equalTo(@[v1.centerYPos.offset(70),v2.centerYPos.offset(15),permitLayout.centerYPos.offset(15),linkLayout.centerYPos.offset(15),self.loginBtn.centerYPos.offset(70)]);
    return layout;
}

#pragma mark -- Layout Construction

-(UILabel*)createLabel:(NSString*)title backgroundColor:(UIColor*)color
{
    UILabel *v = [UILabel new];
    v.backgroundColor = color;
    v.text = title;
    v.font = [CFTool font:17];
    v.textAlignment = NSTextAlignmentCenter;
    [v sizeToFit];
    v.layer.shadowOffset = CGSizeMake(3, 3);
    v.layer.shadowColor = [CFTool color:4].CGColor;
    v.layer.shadowRadius = 2;
    v.layer.shadowOpacity = 0.3;
    
    
    return v;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (UILabel *)loginLabel
{
    if (!_loginLabel) {
        _loginLabel = [[UILabel alloc] init];
        _loginLabel.text = @"登录";
        _loginLabel.font = [CFTool font:36];
        _loginLabel.textColor = [UIColor colorWithHexString:@"#FFFFFF"];
        _loginLabel.textAlignment = NSTextAlignmentCenter;
        [_loginLabel sizeToFit];
    }
    return _loginLabel;
}

- (RPAccountView *)accountView
{
    if (!_accountView) {
        _accountView = [[RPAccountView alloc] init];
        _accountView.accountField.delegate = self;

    }
    return _accountView;
}

- (RPPasswordView *)passwordView
{
    if (!_passwordView) {
        _passwordView = [[RPPasswordView alloc] init];
    }
    return _passwordView;
}

- (UIButton *)btnSelect {
    if (!_btnSelect) {
        _btnSelect = [[UIButton alloc]init];
        [_btnSelect setImage:IOSImageWithName(@"passwordRemSelect") forState:UIControlStateSelected];
        [_btnSelect setImage:IOSImageWithName(@"passwordRemSelectNo") forState:UIControlStateNormal];
        IOSWeakSelf
        [_btnSelect addTapBlock:^(UIButton *btn) {
//            if (weakSelf.selectBlock) {
//                weakSelf.selectBlock();
//            }
//            [weakSelf updateCell:!weakSelf.selectFlag];
            weakSelf.btnSelect.selected = !weakSelf.btnSelect.selected;
            [RPDBManage.share updateUserName:weakSelf.accountView.accountField.text state:weakSelf.btnSelect.selected];
        }];
    }
    return _btnSelect;
}

- (UILabel *)permitLabel
{
    if (!_permitLabel) {
        _permitLabel = [[UILabel alloc] init];
        _permitLabel.text = @"查询并同意个人信息保护政策和用户隐私协议";
        _permitLabel.font = [CFTool font:12];
        _permitLabel.textColor = [UIColor colorWithHexString:@"#FFFFFF"];
        _permitLabel.textAlignment = NSTextAlignmentCenter;
        [_permitLabel sizeToFit];
    }
    return _permitLabel;
}


- (UIButton *)securePrivacybtn
{
    if(!_securePrivacybtn) {
        UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [myButton setTitle:@"个人信息保护政策" forState:UIControlStateNormal];
        [myButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        myButton.titleLabel.font = [UIFont systemFontOfSize:12];
        _securePrivacybtn = myButton;
        [myButton addTapBlock:^(UIButton *btn) {
            RPCWKWebViewController *safariVC = [[RPCWKWebViewController alloc] init];
            [safariVC loadWebURLSring:RPSecurePermit];
            safariVC.isNavHidden = NO;
            [self.navigationController pushViewController:safariVC animated:YES];
        }];
    }
    return _securePrivacybtn;
}

- (UIButton *)securePermitbtn
{
    if(!_securePermitbtn) {
        UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [myButton setTitle:@"用户隐私协议" forState:UIControlStateNormal];
        [myButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        myButton.titleLabel.font = [UIFont systemFontOfSize:12];
        _securePermitbtn = myButton;
        [myButton addTapBlock:^(UIButton *btn) {
            RPCWKWebViewController *safariVC = [[RPCWKWebViewController alloc] init];
            [safariVC loadWebURLSring:RPSecurePrivacy];
            safariVC.isNavHidden = NO;
            [self.navigationController pushViewController:safariVC animated:YES];
        }];
    }
    return _securePermitbtn;
}



- (UIButton *)loginBtn
{
    if (!_loginBtn) {
        _loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_loginBtn setBackgroundColor:[UIColor whiteColor]];
        [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        _loginBtn.titleLabel.font = [UIFont systemFontOfSize:17];
        _loginBtn.layer.cornerRadius = 5.0f;
        _loginBtn.layer.masksToBounds = YES;
        [_loginBtn setTitleColor:[UIColor colorWithHexString:@"#4BA8FF"] forState:UIControlStateNormal];
        [_loginBtn addTarget:self action:@selector(loginBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginBtn;
}

- (NSString *)sm2Encode:(NSString *)pubKey text:(NSString *)text
{
//    NSString *pubKey = @"MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEgZiuTaBHYtiS297zSElG0bT1Qsg7e0mOCG6dQVOboXgcA7zTpYLCAYiGCFsfJrZLoeZ6zo/kbZ7twaZL5foIYw==";
    NSArray *pemList = @[@"-----BEGIN PUBLIC KEY-----", pubKey,
                         @"-----END PUBLIC KEY-----"];
    NSString *pemPubKey = [pemList componentsJoinedByString:@"\n"];
    NSString *pubKeyHex = [GMSm2Bio readPublicKeyFromPemString:pemPubKey];
    NSString *enstr  = [GMSm2Utils encryptText:text publicKey:pubKeyHex];
    NSString *decryptASN1 = [GMSm2Utils asn1DecodeToC1C3C2:enstr];
    NSString *decryptC1C2C3 = [GMSm2Utils convertC1C3C2ToC1C2C3:decryptASN1 hasPrefix:NO];
    NSString *base64Cipertext = [GMUtils base64Encode:[GMUtils hexToData:[NSString stringWithFormat:@"04%@",decryptC1C2C3]]];
//    NSLog(@"========== base64Cipertext:%@", base64Cipertext);
    return base64Cipertext;
}

- (void)loginBtnClick:(UIButton *)btn
{
#if 0
    NSArray *array = @[@1];
    NSLog(@"%@",array[2]);
#endif

    NSInteger error = 0;
    NSString *encryptStr = [self.passwordView.accountField getEncryptedDataWithError:&error];
    if (encryptStr == nil) {
        encryptStr = @"";
    }
    
    NSString *clientRandom = [self.passwordView.accountField getEncryptedClientRandomWithError:&error];
    
    if (!self.accountView.accountField.text.isNotBlank) {
        [QMUITips showError:@"登入账号不能为空" inView:self.view hideAfterDelay:2];
        return;
    }
    if (!encryptStr.isNotBlank) {
        [QMUITips showError:@"密码不能为空" inView:self.view hideAfterDelay:2];
        return;
    }
    
    if (!RPCompany.isNotBlank) {
        [QMUITips showError:@"运营机构不能为空" inView:self.view hideAfterDelay:2];
        return;
    }
    if (!RPOrgan.isNotBlank) {
        [QMUITips showError:@"企业代码不能为空" inView:self.view hideAfterDelay:2];
        return;
    }
    if (!RPAccount.isNotBlank) {
        [QMUITips showError:@"登入账号不能为空" inView:self.view hideAfterDelay:2];
        return;
    }
    if (!RPURL.isNotBlank) {
        [QMUITips showError:@"服务器地址不能为空" inView:self.view hideAfterDelay:2];
        return;
    }
    if (!RPPort.isNotBlank) {
        [QMUITips showError:@"服务器端口不能为空" inView:self.view hideAfterDelay:2];
        return;
    }
    

    
    void (^toLoginBlock)(void) = ^() {
        //#define RPCompany RPDataManager.sharedInstance.company
        //#define RPOrgan RPDataManager.sharedInstance.organ
        //#define RPAccount RPDataManager.sharedInstance.acount
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        //    hud.mode = MBProgressHUDModeDeterminate;
        hud.label.text = @"Loading";
        
        weakify(self);
        [[[[self secureTime] then:^id _Nullable(RPSecureTimeModel * _Nullable value) {
            strongify(self);
            NSString *sm2PublicKey = getValidString(value.k);
            [NSUserDefaults.standardUserDefaults setValue:sm2PublicKey forKey:@"sm2PublicKey"];
            NSString *sendtime = value.t;
            NSMutableDictionary *requestMap = @{}.mutableCopy;
            [requestMap setValue:RPCompany forKey:@"company"]; /// 机构
            [requestMap setValue:RPOrgan forKey:@"organ"]; /// 机构
            [requestMap setValue:RPAccount forKey:@"account"]; /// 账号
            [requestMap setValue:getValidString(sendtime) forKey:@"sendtime"]; /// 时间
            [requestMap setValue:getValidString(encryptStr) forKey:@"password"]; /// 密码
            [requestMap setValue:@"MDEyMzQ1Njc4OWFiY2RlZg==" forKey:@"serverRandom"]; ///服务器返回的时间戳
            [requestMap setValue:clientRandom forKey:@"clientRandom"]; ///客户端随机数   由银行安全控件提供
            if(UIDevice.currentDevice.isJailbroken) {
                [requestMap setValue:@1 forKey:@"env_code"]; ///是否越狱
                [requestMap setValue:@"当前设备已越狱" forKey:@"env_message"]; ///是否越狱
            }else{
                [requestMap setValue:@0 forKey:@"env_code"]; ///是否越狱
            }
            // 生产 sm4 密钥，注意为 16 字节字母数字符号混合的字符串
            NSString *sm4Prikey = @"BB310F6B74408F3B";
            NSString * messageEncrypt  =  [[GMUtils hexToData:[GMSm4Utils cbcEncryptText:requestMap.mj_JSONString key:[GMUtils stringToHex:sm4Prikey] IV:[GMUtils stringToHex:@"abcdefghABCDEFGH"]]] base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
            NSMutableDictionary *mobileMap = @{}.mutableCopy;
            [mobileMap setValue:messageEncrypt forKey:@"messageEncrypt"];
            [mobileMap setValue:[self sm2Encode:sm2PublicKey text:@"4BFBC78BE1B5030F3C1593626AF201B0"] forKey:@"messageCode"];
            [mobileMap setValue:[GMSm3Utils hashWithString:requestMap.mj_JSONString] forKey:@"messageHash"];
            
            NSLog(@"requestMap:%@\n",requestMap.mj_JSONString);
            NSLog(@"messageCode:%@\n",@"4BFBC78BE1B5030F3C1593626AF201B0");
            NSLog(@"messageHash:%@\n",requestMap.mj_JSONString);
            return [self secureMobile:mobileMap];
        }] then:^id _Nullable(RPSecureMobileModel *value) {
            strongify(self);
            RPGloabManage.sharedInstance.mobileModel = value;
            [hud hideAnimated:YES];
            WKWebViewController *web = [[WKWebViewController alloc] init];
            web.result = value.user_token;
            [web loadWebHTMLSring:@"h5/index"];
            web.isNavHidden = YES;
            self.passwordView.accountField.text = @"";
            [self.navigationController pushViewController:web animated:YES];
            return nil;
        }] catch:^(NSError * _Nonnull error) {
            strongify(self);
            [hud hideAnimated:YES];
            [self clearPassword];
        }];
    };
    

    if(self.btnSelect.selected) {
        NSInteger flag = [NSUserDefaults.standardUserDefaults integerForKey:@"currentUser"];
//        if (!flag) {
//            [NSUserDefaults.standardUserDefaults removeObjectForKey:BCJPrivateProtocolAlertDefaultsKey];
//            [BCJPrivateProtocolAlert showWithModel:[ BJCPrivateProtocolModel new ] block:^{
//                [NSUserDefaults.standardUserDefaults setBool:YES forKey:@"currentUser"];
//                toLoginBlock();
//            }];
//        }else{
//            toLoginBlock();
//        }
        toLoginBlock();
    }else{
        [QMUITips showError:@"请先查询并同意个人信息保护政策和用户隐私协议" inView:self.view hideAfterDelay:2];
    }
}

- (FBLPromise <RPSecureTimeModel *>*)secureTime
{
    return [FBLPromise onQueue:dispatch_get_main_queue() async:^(FBLPromiseFulfillBlock  _Nonnull fulfill, FBLPromiseRejectBlock  _Nonnull reject) {
//        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//        manager.responseSerializer = [AFHTTPResponseSerializer serializer];// 响应
//        manager.securityPolicy = [AFSecurityPolicy defaultPolicy];
//        manager.securityPolicy.allowInvalidCertificates = YES;
//        [manager.securityPolicy setValidatesDomainName:NO];
//
//        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain", @"text/html", nil];
        AFHTTPSessionManager *manager = [RPNetworkUitls getNetworkManager];
        NSMutableDictionary *param  = @{@"company":RPCompany,
                                        @"organ":RPOrgan,
                                        @"account":RPAccount
        }.mutableCopy;
        
//        @"https://121.4.208.208:843/secureTime"
//        RPCsecureMobile
        [manager POST:RPCsecureTime parameters:param headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            RPSecureTimeModel *model = [RPSecureTimeModel yy_modelWithJSON:responseObject];
            if (model.isSuccess) {
                fulfill(model);
            }else{
                reject(model.error);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"====:%@",error),
            reject(error);
        }];
    }];
}


- (FBLPromise *)secureMobile:(NSDictionary *)param
{
    return [FBLPromise onQueue:dispatch_get_main_queue() async:^(FBLPromiseFulfillBlock  _Nonnull fulfill, FBLPromiseRejectBlock  _Nonnull reject) {
//        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
//        manager.responseSerializer = [AFHTTPResponseSerializer serializer];// 响应
//        manager.securityPolicy = [AFSecurityPolicy defaultPolicy];
//        manager.securityPolicy.allowInvalidCertificates = YES;
//        [manager.securityPolicy setValidatesDomainName:NO];
//        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain", @"text/html", nil];

        AFHTTPSessionManager *manager = [RPNetworkUitls getNetworkManager];
//        @"https://121.4.208.208:843/secureMobile"
        [manager POST:RPCsecureMobile parameters:param headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            RPSecureMobileModel *model = [RPSecureMobileModel yy_modelWithJSON:responseObject];
            if (model.isSuccess) {
                fulfill(model);
            }else{
                reject(model.error);
            }
//            NSError *error = [NSError errorWithDomain:@"renpho.com" code:9999 userInfo:@{NSLocalizedDescriptionKey:@"错误信息"}];
//            reject(error);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            reject(error);
        }];
    }];
}



- (void)clearPassword
{
    self.passwordView.accountField.text = @"";
}

//- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//    // 在这里处理输入事件
//    Boolean select  =  [RPDBManage.share queryUserName:string];
//    self.btnSelect.selected = select;
//    return YES;
//}

- (void)textFieldDidChangeSelection:(UITextField *)textField
{
    Boolean select  =  [RPDBManage.share queryUserName:textField.text];
    self.btnSelect.selected = select;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    // 在这里处理结束编辑事件
    Boolean select  =  [RPDBManage.share queryUserName:textField.text];
    self.btnSelect.selected = select;
}
@end
